package com.asia.algorithmcode.backTracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 132、分割回文串2
 */
public class Partition_mincut {


    public static void main(String[] args) {
        String s = "aab";


        System.out.println(new Partition_mincut().minCut(s));

    }

    public int minCut(String s) {
        int n = s.length();
        boolean[][] f = new boolean[n][n];

        // 预处理 f[i][j]：判断 s[i..j] 是否回文
        for (int i = 0; i < n; i++) {
            Arrays.fill(f[i], true);
        }
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                f[i][j] = (s.charAt(i) == s.charAt(j)) && f[i + 1][j - 1];
            }
        }

        // dp[i]：s[0..i] 最小切割次数
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);

        for (int i = 0; i < n; i++) {
            if (f[0][i]) {
                dp[i] = 0; // 整段回文不用切
            } else {
                for (int j = 0; j < i; j++) {
                    if (f[j + 1][i]) {
                        dp[i] = Math.min(dp[i], dp[j] + 1);
                    }
                }
            }
        }

        return dp[n - 1];
    }


}
